package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.Result;
import com.itheima.domain.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/10/9 19:15
 */

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;


    @RequestMapping("/login")
    public Result login(@RequestBody Map map, HttpServletResponse response) {
        //获取验证码,判断验证码是否正确;
        String validateCode = map.get("validateCode").toString();
        //从redis中取出验证码进行校验;
        String telephone = map.get("telephone").toString();
        String redisCode = jedisPool.getResource().get(telephone + "_002");
        //判断验证码是否正确;
        if (validateCode != null && validateCode.equals(redisCode)) {
            //通过手机号查询是不是会员;
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                member = new Member();
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                memberService.add(member);
            }
            //向客户端中写入cookie;
            Cookie cookie = new Cookie("member_telephone", telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 30 * 24);
            response.addCookie(cookie);
            String cookStr = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone + "_003", 60 * 60, cookStr);
            return new Result(true, "登陆成功");
        } else {
            return new Result(false, "无效的验证码!");
        }
    }
}
